package at.tuwien.seminar.scrum1.proxies;

import at.tuwien.seminar.scrum1.hibernate.HibernateUtil;
import at.tuwien.seminar.scrum1.model.Bill;
import at.tuwien.seminar.scrum1.model.Customer;
import at.tuwien.seminar.scrum1.model.Room;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;

public class BillProxy {

	private static BillProxy instance;
	private EntityManager em;

	private BillProxy() {
		em = HibernateUtil.getEntityManagerFactory().createEntityManager();
	}

	public static BillProxy getInstance() {
		return instance == null ? instance = new BillProxy() : instance;
	}

	public List<Bill> getAll() {
       	
		return getAll(em);
	}
	
	public List<Bill> getAll(EntityManager em) {
       	return (List<Bill>)em.createQuery("from Bill").getResultList();
	}
	

	public long insertBill(Bill bill)
	{
		return insertBill(bill,em);
	}
	
	public long insertBill(Bill bill, EntityManager em)
	{
		em.getTransaction().begin();

        List<Customer> customers = new ArrayList<Customer>();

        for (Customer cust : bill.getCustomers()) {
            customers.add(em.createQuery("from Customer WHERE id=:id", Customer.class).setParameter("id", cust.getId()).getSingleResult());
        }

        bill.setCustomers(customers);

		em.persist(bill);
		em.getTransaction().commit();
		
		return bill.getId();
	}
	

}
